package com.easyCms.base.utils;

import java.io.IOException;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;

public class HttpClientUtils {
	public static String post(String url, String requestData) throws ClientProtocolException, IOException {
		CloseableHttpClient client = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);
		httpPost.setHeader("Content-Type", "application/json");

		if (StringUtils.isNoneBlank(new CharSequence[] { requestData })) {
			StringEntity data = new StringEntity(requestData, "UTF-8");
			data.setContentType("text/json");
			data.setContentEncoding(new BasicHeader("Content-Type", "application/json"));
			httpPost.setEntity(data);
		}

		CloseableHttpResponse response = client.execute(httpPost);

		HttpEntity entity = response.getEntity();
		if (entity != null) {
			return EntityUtils.toString(entity, "UTF-8");
		}
		return "";
	}

	public static String get(String url) throws ClientProtocolException, IOException {
		CloseableHttpClient client = HttpClients.createDefault();
		HttpGet httpGet = new HttpGet(url);
		httpGet.setHeader("Content-Type", "application/json");

		CloseableHttpResponse response = client.execute(httpGet);

		HttpEntity entity = response.getEntity();
		if (entity != null) {
			return EntityUtils.toString(entity, "UTF-8");
		}
		return "";
	}
}